using System;
using System.ComponentModel;
using System.Diagnostics;
using System.Windows.Forms;
using DevExpress.XtraEditors;
using DevExpress.XtraEditors.Controls;
using Pharmacy.Data.Entity;
using System.Collections.Generic;


namespace PharmacyPharnet.Core
{
	/// <summary>
	/// Summary description for ControlViewBase.
	/// </summary>
	public class ControlViewBase : XtraUserControl, IView
	{
		#region Default Component Designer generated code

		/// <summary> 
		/// Required designer variable.
		/// </summary>
		private System.ComponentModel.Container components = null;

		public ControlViewBase()
		{
			// This call is required by the Windows.Forms Form Designer.
			InitializeComponent();		
		}

		/// <summary> 
		/// Clean up any resources being used.
		/// </summary>
		protected override void Dispose( bool disposing )
		{
			if( disposing )
			{
				if(components != null)
				{
					components.Dispose();
				}
			}
			base.Dispose( disposing );
		}

		/// <summary> 
		/// Required method for Designer support - do not modify 
		/// the contents of this method with the code editor.
		/// </summary>
		private void InitializeComponent()
		{
            this.SuspendLayout();
            // 
            // ControlViewBase
            // 
            this.Name = "ControlViewBase";
            this.Padding = new System.Windows.Forms.Padding(4);
            this.ResumeLayout(false);

		}
		#endregion

		#region Override methods        

        /// <summary>
        /// Fired when the View is loaded.
        /// </summary>
        /// <param name="e"></param>
        /// <author></author>
        /// <history>
        /// 2011.01.26 - ThangTran: added Xml-doc, added code to call ApplyUserPermissionOnToolBar().
        /// 2011.05.23 - ThangTran: moved ApplyLanguage() to outside of the try-catch.
        /// </history>
		protected override void OnLoad(EventArgs e)
		{
            try
            {	
                // TODO: Add any initialization after the InitForm call
                InitializeBO();
                
                PopulateStaticData();
                //12/22/2010 nghiemhoang upd stt
                //GetGridData();
                //PopulateGrid();
                //FilterConfig filterConfig = new FilterConfig(this);
                //if (filterConfig.isUseFilterConfig)
                //{
                //    bool rtn = filterConfig.Load();
                //}
                //else
                //{
                    GetGridData();
                    PopulateGrid();
                //}
                //12/22/2010 nghiemhoang upd end  

                // automatically apply user permission
                this.ApplyUserPermissionOnToolBar();

                SetFocusedIndex();                
                DisableControlsWithoutPermission();                

                base.OnLoad(e);
            }
            catch (Exception ex)
            {
                //NotifyUserUtil.ShowException(ex);
            }

            // ThangTran - moved ApplyLanguage() to outside of the try-catch to force localizing it even when getting error
            try
            {
                // Apply localize
                LocalizerView.ApplyLanguage(this);
            }
            catch (Exception ex)
            {
                //NotifyUserUtil.ShowException(ex);
            }


			Disposed += new EventHandler(ControlViewBase_ReleaseLock);
            //TODO: Ho commented: Test whether this commented generates error ?
			//VisibleChanged += new EventHandler(ControlViewBase_ReleaseLock);
		}


		#endregion

		/// <summary>
		/// Initialize the instance of all busuness object which used in the view
		/// </summary>
		protected virtual void InitializeBO()
		{
		}
		/// <summary>
		/// Confirm the allowed permissions with the bussiness object and then disable/enable the appropriated controls.
		/// </summary>
		protected virtual void DisableControlsWithoutPermission()
		{
		}

		/// <summary>
		/// Populates the data for filter control or the editing control.
		/// </summary>
		protected virtual void PopulateStaticData()
		{
		}
		/// <summary>
		/// Consult to the business object to get the data for the grid control on view.
		/// </summary>
		protected virtual void GetGridData()
		{
		}
		/// <summary>
		/// Populates the data on the grid control and do some adjustment on look and feel.
		/// </summary>
		protected virtual void PopulateGrid()
		{
		}

		protected virtual void SetFocusedIndex()
		{

		}
		/// <summary>
		/// Releases the lock on objects. This class will be automatically invoked by the Main form
		/// </summary>
		protected virtual void ReleaseLockOnObjects()
		{
		}

        protected virtual void DisposeSessionKey() {
        }
		/// <summary>
		/// Handles the Disposed event of the ControlViewBase control to release the lock when the control is removed from the main form.
		/// </summary>
		private void ControlViewBase_ReleaseLock(object sender, EventArgs e)
		{
			try
			{
				ReleaseLockOnObjects();
                DisposeSessionKey();
			}
			catch(Exception ex)
			{
                //NotifyUserUtil.ShowException(ex);
			}
		}

        #region IView Members

	    /// <summary>
	    /// Gets or sets feature name of this View.
	    /// </summary>
	    private string _featureTypeName;

        /// <summary>
        /// Gets or sets feature name of this View.
        /// </summary>
        public string FeatureTypeName
        {
            get
            {
                return _featureTypeName ?? (_featureTypeName = this.GetType().FullName);
            }
            set
            {
                // --- Begin parameters checking code -----------------------------
                Debug.Assert(value != null);  // this field can't accept null value
                // --- End parameters checking code -------------------------------

                _featureTypeName = value;
            }
        }

        /// <summary>
        /// Gets a value that indicates whether this View is closed or not.
        /// </summary>
        private bool _isClosed;

        /// <summary>
        /// Gets a value that indicates whether this View is closed or not.
        /// </summary>
        public bool IsClosed
        {
            get { return _isClosed; }
            set { _isClosed = value; }
        }

        /// <summary>
        /// Gets a value that indicates wheter the event is prevented or not.
        /// </summary>        
        private bool _eventIsPrevented;

        /// <summary>
        /// Gets a value that indicates wheter the event is prevented or not.
        /// </summary>
        public bool EventIsPrevented
        {
            get { return _eventIsPrevented; }
            protected set { _eventIsPrevented = value; }


        }

        /// <summary>
        /// Applies current logging in user's permission to all toolbars on this View.
        /// </summary>
        public void ApplyUserPermissionOnToolBar()
        {
            // call extension method to avoid duplicating code
            ViewHelper.ApplyUserPermissionOnToolBar(this);
        }

        #endregion        

        /// <summary>
        /// 
        /// </summary>
        /// <param name="functionName"></param>
        /// <param name="functions"></param>
        /// <retuns></returns>
        /// <author></author>
        /// <history>
        /// 2011.01.25 - ThangTran: copied code from ControlViewBase to quick-fix the Enable/Disable menubar items issue.
        /// </history>
        private bool CheckIsEnable(string functionName, List<Function> functions)
        {
            bool isEnable = false;
            foreach (Function function in functions)
            {
                if (function.Name == functionName)
                {
                    isEnable = true;
                    break;
                }
            }

            return isEnable;
        }

        /// <summary>
        /// 
        /// </summary>
        /// <param name="functionName"></param>
        /// <param name="functions"></param>
        /// <returns></returns>
        /// <author></author>
        /// <history>
        /// 2011.01.25 - ThangTran: copied code from ControlViewBase to quick-fix the Enable/Disable menubar items issue.
        /// </history>
        private bool CheckIsVisible(string functionName, List<Function> functions)
        {
            bool isVisible = false;
            foreach (Function function in functions)
            {
                if (function.Name == functionName)
                {
                    isVisible = function.IsVisible.GetValueOrDefault();
                    break;
                }
            }

            return isVisible;
        }
    }
}

